#pragma once
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root)
    {
        vector<vector<int>> vv;
        if (root == nullptr)
            return vv;

        queue<TreeNode*> q;
        q.emplace(root);
        int levelCount = 1;

        while (levelCount > 0)
        {
            vector<int> v;
            while (levelCount--)
            {
                TreeNode* front = q.front();
                q.pop();

                if (nullptr != front->left)
                    q.emplace(front->left);

                if (nullptr != front->right)
                    q.emplace(front->right);

                v.emplace_back(front->val);
            }
            levelCount = q.size();
            vv.emplace_back(v);
        }
        reverse(vv.begin(), vv.end());

        return vv;
    }
};
